import { WebviewWindow, getCurrentWebviewWindow } from '@tauri-apps/api/webviewWindow';
import { openUrl, openPath } from '@tauri-apps/plugin-opener';
import { tempDir, appDataDir, join } from '@tauri-apps/api/path';
import { exists, mkdir, writeFile } from '@tauri-apps/plugin-fs';
import { save } from '@tauri-apps/plugin-dialog';
import { open, Command } from '@tauri-apps/plugin-shell';

type DialogOptions = {
    title?: string;
    url?: string;
    focus?: boolean;
    width?: number;
    height?: number;
    maximized?: boolean;
};

const defaultOptions = {
  focus: true,
};

/**
 * 打开窗口
 * @param options 
 */
export const openDialog = async (options : DialogOptions) => {
  const o = Object.assign(defaultOptions, options)
  const webview = new WebviewWindow('webview', o);
  webview.once('tauri://created', function () {
  // webview successfully created
    // webview.setDecorations(false);
  });
  webview.once('tauri://error', function (e) {
    // an error happened creating the webview
    console.error(e)
  });
};

/**
 * 设置标题
 * @param title 
 */
export const setTitle = async (title: string) => {
  const window = await getCurrentWebviewWindow();
  window.setTitle(title);
};

export const openWeb = async (path: string) => {
  await openUrl(path);
};

export const previewImg = async (url: string) => {
  const tempPath = await tempDir();
  console.log("tempPath:", tempPath)
  const arr = url.split('/');
  const fileName = arr[arr.length - 1];
  console.log("fileName:", fileName)
  const suffix = fileName.split('.')[1];
  const filePath = await downloadRemoteFile(url, '', tempPath +  new Date().getTime() + '.' + suffix);
  if (filePath) {
    await openPath(filePath);
  }
};

export const getSavePath = async (fileName: string) => {
  // 选项 1：保存到应用数据目录
  // const appDataPath = await appDataDir();
  // return `${appDataPath}/${fileName}`;

  // 选项 2：让用户选择保存位置
  const filePath = await save({
    // filters: [
    //   { name: 'All Files', extensions: ['*'] }
    // ],
    defaultPath: fileName
  });
  return filePath;
};

export const downloadRemoteFile = async (url: string, fileName: string, path: string = '') => {
  try {
    // 获取远程文件的二进制数据
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const blob = await response.blob();
    const arrayBuffer = await blob.arrayBuffer();
    const data = new Uint8Array(arrayBuffer);

    // 获取保存路径
    let filePath = path;
    if (!filePath) {
      filePath = await getSavePath(fileName) || '';
    }

    if (filePath) {
      // 将文件写入本地
      await writeFile(filePath, data);
      console.log(`File saved to: ${filePath}`);
    }
    return filePath;
  } catch (error) {
    console.error('Error downloading file:', error);
    throw error;
  }
};

export const openFolder = async (rootPath: string, folderPath: string = '') => {
  let appPath  = rootPath;
  if (!appPath) {
    appPath = await appDataDir();
  }
  const fullPath = await join(appPath, folderPath);
  let pathExists = false;
  // 检查文件夹是否存在
  try {
    pathExists = await exists(fullPath);
  } catch (error) {}
  
  if (!pathExists) {
    await mkdir(fullPath, { recursive: true });
  }
  
  try {
    await open(fullPath);  
  } catch (error) {
    console.log(error) 
  }
};

export default openDialog;